package com.mediacloud.app.newsmodule.fragment


import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.FrameLayout
import android.widget.GridView
import android.widget.ImageView
import androidx.annotation.RequiresApi
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.request.RequestOptions
import com.flyco.tablayout.SlidingTabLayout
import com.google.android.material.appbar.AppBarLayout
import com.mediacloud.app.adapter.ComponentRecyclerAdapter
import com.mediacloud.app.assembly.util.Reflect
import com.mediacloud.app.assembly.util.Utility
import com.mediacloud.app.assembly.util.load
import com.mediacloud.app.fbnavsk.navPaddingTopMatch
import com.mediacloud.app.model.component.ComponentItem
import com.mediacloud.app.model.interfaces.DataInvokeCallBack
import com.mediacloud.app.model.news.ArticleListData
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.news.kt.TypeX
import com.mediacloud.app.nav2.fragment.HqyNavFragment
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.adaptor.component.ComponentListItemStyleAdaptor
import com.mediacloud.app.newsmodule.utils.NewsListDataInvoker
import com.mediacloud.app.newsmodule.utils.load
import com.mediacloud.app.newsmodule.utils.readData
import com.mediacloud.app.newsmodule.utils.saveData
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig
import com.mediacloud.app.reslib.enums.ToolBarActionF5OrTop
import com.mediacloud.appcloud.project.gxapp.model.utils.MD5Util
import com.zimeiti.activity.*
import kotlinx.android.synthetic.main.fragment_blank_pagex.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.json.JSONArray
import org.json.JSONException


/**
 * 强军号
 */
class NewBlankPageFragmentX : HqyNavFragment(),
    DataInvokeCallBack<ArticleListData>, ToolBarActionF5OrTop {

    val titles: MutableList<String> = ArrayList()
    var catalogs: MutableList<CatalogItem> = ArrayList()
    val fragments: MutableList<Fragment> = ArrayList()
    var adapter: PagerAdapter? = null
    var catalogID: String? = null
    var componentAdapter: ComponentListItemStyleAdaptor? = null
    var catalogItem: CatalogItem? = null
    var dataInvoker: NewsListDataInvoker? = null
    var tabComponentItem: ComponentItem? = null
    var c89Item: ComponentItem? = null
    var c89ContentItem: MutableList<ComponentItem>? = null
    var adapterComponent: ComponentRecyclerAdapter<ComponentItem>? = null

    override fun getLayoutResID(): Int {
        return R.layout.fragment_blank_pagex
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        navPaddingTopMatch()
        GlobalScope.launch {

        }
        if (fragmentArguments != null) {
            saveInstanceArguments = fragmentArguments
            catalogID = saveInstanceArguments?.getString("id")
            catalogItem = saveInstanceArguments?.getParcelable("catalog")
        } else if (saveInstanceArguments != null) {
            catalogID = saveInstanceArguments!!.getString("id")
            catalogItem = saveInstanceArguments!!.getParcelable("catalog")
        }
        componentAdapter = ComponentListItemStyleAdaptor(requireContext(), catalogItem)

        dataInvoker = NewsListDataInvoker(this)
        refreshLayout.setEnableLoadMore(false)

        val dataResult = this.readData("$catalogID", ArticleListData::class.java)
        if (dataResult != null && (dataResult.articleList.size > 0 || dataResult.componentItems.size > 0)) {
            success(dataResult)
        } else {
            getData()
        }


    }

    private fun getData() {
        dataInvoker?.getContentList(catalogID, 1, 1, null)
    }

    override fun initView() {
        loadingView = findViewById(R.id.mLoadingView);
        initStateView();
        retryTips?.setOnClickListener {
            if (currentState != TYPE_LOADING) {
                showStateView(TYPE_LOADING, false)
                getData()
            }
        }
        showStateView(TYPE_LOADING, false)
        refreshLayout.setOnRefreshListener {
            getData()
        }

    }

    var oldMd5 = ""

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun success(data: ArticleListData?) {
        if (activity==null||requireActivity().isFinishing||requireActivity().isDestroyed){
            return
        }
        //不是上次的缓存数据才进行缓存
        val isCacheData = data?.orginData?.optInt("is_cache", 0) == 1
        if (!isCacheData) {
            try {
                data?.orginData?.put("is_cache", 1)
                saveData("$catalogID", data?.orginData.toString() + "")
            } catch (e: JSONException) {
                e.printStackTrace()
            }
        }
        refreshLayout.finishRefresh()
        if (data?.state == true) {

            val componentList = data.componentItems
            val stringBuffer = StringBuffer()
            for (i in componentList.indices) {
                stringBuffer.append(componentList.get(i).getOrginData())
            }
//            val md5 = MD5Util.MD5Encode(stringBuffer.toString(), "UTF-8")
//            if (oldMd5 == md5) {
//                Log.w("YOAKE", "组件数据没变。不刷新界面")
//                return
//            } else {
                componentContainer.removeAllViews()
                tabComponentItem = null
                componentAdapter?.listContentData = componentList
                componentAdapter?.clearEvent()
                val size = componentList.size
                for (index in 0 until size) {
                    val item = componentList[index]
                    if (item.widget == TypeX.COMPONENT_X.C999912 || item.widget == TypeX.COMPONENT_X.C999988) {
                        tabComponentItem = item
                        break
                    }
                    if (item.widget == TypeX.COMPONENT_X.C999989 || c89Item != null) {
                        if (c89Item == null) {
                            c89Item = item
                            c89ContentItem = ArrayList()
                        } else {
                            c89ContentItem?.add(item)
                        }
                    } else {
                        val view = componentAdapter?.getView(index, null, null) ?: continue
                        componentContainer.addView(view, -1, -2)
                    }
                }
                c89Item?.let {
                    setComponent89(it, c89ContentItem!!)
                }

                closeStateView()
//            }
//            oldMd5 = md5
        }
        tabComponentItem?.let {
            buildTab(it)
        }

        if (isCacheData) {
            refreshLayout.autoRefresh()
        }
    }

    override fun fault(data: Any?) {
        if (activity==null||requireActivity().isFinishing||requireActivity().isDestroyed){
            return
        }
        refreshLayout.finishRefresh()
        refreshLayout.setEnableLoadMore(false)
        closeStateView();
    }


    private fun buildTab(componentItem: ComponentItem) {

        titles.clear()
        catalogs.clear()
        fragments.clear()

        val view = LayoutInflater.from(requireContext()).inflate(R.layout.item_component_tabx, componentContainer, true)
        val tabImage: ImageView = view.findViewById(R.id.tabImage)
        val tabContainer: View = view.findViewById(R.id.tabContainer)
        val tabLayout: SlidingTabLayout = view.findViewById(R.id.tabLayout)

        val viewPager = MConsecutiveViewPagerX(requireContext())
        val viewPagerLp = CoordinatorLayout.LayoutParams(-1, -1)
        viewPager.id = View.generateViewId()
        viewPagerLp.behavior = AppBarLayout.ScrollingViewBehavior()
        coordinator.addView(viewPager, viewPagerLp)

        val tabImageLp = tabImage.layoutParams as ViewGroup.MarginLayoutParams
        tabImageLp.height = resources.getDimensionPixelSize(R.dimen.dimen40)
        tabContainer.setBackgroundColor(Color.WHITE)
        var width_as_screen = false
        try {
            val other_field = componentItem.orginDataObject.optJSONObject("other_field")
            val font_default_color = other_field.optString("font_default_color")
            val font_selected_color = other_field.optString("font_selected_color")
            val selected_color = Color.parseColor(font_selected_color)
            tabLayout.textUnselectColor = Color.parseColor(font_default_color)
            tabLayout.textSelectColor = selected_color
            val is_selected_underline = other_field.optInt("is_selected_underline")

            val font_default_size = other_field.optInt("font_default_size", 20)
            val font_selected_size = other_field.optInt("font_selected_size", 20)
            if (is_selected_underline == 0) {
                tabLayout.indicatorHeight = 0F
            } else {
                tabLayout.indicatorColor = (selected_color)
                tabLayout.indicatorHeight = (resources.getDimensionPixelSize(R.dimen.dimen2)).toFloat()
            }

            Reflect.on(tabLayout).set("mTabTextSize", Utility.dpToPx(requireContext(), font_default_size * 1f) * 1f)
            Reflect.on(tabLayout).set("mTabSelectedTextSize", Utility.dpToPx(requireContext(), font_selected_size * 1f) * 1f)


            if (componentItem.widget == TypeX.COMPONENT_X.C999912) {
                val bg_img = other_field.optString("bg_img")
                if (!TextUtils.isEmpty(bg_img)) {
                    val option = RequestOptions().error(AppFactoryGlobalConfig.defaultImageLoadDrawable)
                    tabImage.load(bg_img, option)
                }

                width_as_screen = other_field.optString("width_as_screen") == "1"
                if (!width_as_screen) {
                    val margin = resources.getDimensionPixelSize(R.dimen.dimen12)
                    tabImageLp.marginStart = margin
                    tabImageLp.marginEnd = margin
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        if (componentItem.widget == TypeX.COMPONENT_X.C999912) {
            val w = Utility.getScreenWidth(requireContext())
            if (width_as_screen) {
                tabImageLp.width = w
                tabImageLp.height = w * componentItem.height / componentItem.width
            } else {
                tabImageLp.width = w - 2 * resources.getDimensionPixelSize(R.dimen.dimen12)
                tabImageLp.height = tabImageLp.width * componentItem.height / componentItem.width
            }
        }
        tabImage.layoutParams = tabImageLp


        val element = componentItem.getElement()
        try {
            val jsonArray = JSONArray(element)
            val length = jsonArray.length()

            for (i in 0 until length) {
                jsonArray.optJSONObject(i)?.let { element ->
                    val item = CatalogItem()
                    val name = element.optString("title", "")
                    item.catname = name
                    element.optJSONObject("navigate")?.let {
                        item.catid = it.optString("id")
                        item.catalog_type = it.optString("category")
                    }

                    titles.add(name)
                    catalogs.add(item)
                   // fragments.add(TabWaterfallFragment.newInstance(item.catid, item/*, d*/))
                    if (componentItem.widget == TypeX.COMPONENT_X.C999988) {
                        fragments.add(TabWaterfallFragmentX.newInstance(item.catid, item/*, d*/))
                    } else {
                        fragments.add(TabListFragmentX.newInstance(item.catid, item/*, d*/))
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        viewPager?.offscreenPageLimit = fragments.size
        adapter = PagerAdapter(fragments, titles, childFragmentManager)
        viewPager?.adapter = adapter
        tabLayout.setViewPager(viewPager)

        if (componentItem.widget == TypeX.COMPONENT_X.C999988) {
            viewPager?.setNoScroll(false)
            if (titles.size <= 1) {
                tabContainer.layoutParams.height = 1
                tabContainer.requestLayout()
            } else {
                tabContainer.visibility = View.VISIBLE
            }
        }
    }


    private fun setComponent89(componentItem: ComponentItem, contentList: MutableList<ComponentItem>) {
        refreshLayout.setEnableLoadMore(false)
        val view = LayoutInflater.from(requireContext()).inflate(R.layout.component_type89x, coordinator, true)
        val girdView: GridView = view.findViewById(R.id.gridView)
        val tabContainer: FrameLayout = view.findViewById(R.id.tabContainer)
        val spanCount = componentItem.getCol()
        girdView.numColumns = spanCount
        val adapter = Adapter(requireContext())
        girdView.adapter = adapter

        adapterComponent = ComponentRecyclerAdapter(requireContext())
        adapterComponent?.catalogItem = catalogItem
        val recyclerView2 = RecyclerView(requireContext())
        val recyclerView2Lp = CoordinatorLayout.LayoutParams(-1, -1)
        recyclerView2.id = View.generateViewId()
        recyclerView2Lp.behavior = AppBarLayout.ScrollingViewBehavior()
        coordinator.addView(recyclerView2, recyclerView2Lp)

        val layoutManager = LinearLayoutManager(requireContext())
        recyclerView2.layoutManager = layoutManager
        recyclerView2.adapter = adapterComponent

        recyclerView2.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                //获取RecyclerView当前顶部显示的第一个条目对应的索引
                val position = layoutManager.findFirstVisibleItemPosition()
                if (position != adapter.selectPosition) {
                    adapter.selectPosition = position
                    adapter.notifyDataSetChanged()
                }

            }
        })

        girdView.setOnItemClickListener { parent, view, position, id ->
            val location = IntArray(2)
            girdView.getLocationOnScreen(location)
            val x = location[0] //获取当前位置的横坐标
            val y = location[1] //获取当前位置的纵坐标
            coordinator.scrollTo(0, y)
            adapter.selectPosition = position
            adapter.notifyDataSetChanged()
            layoutManager.scrollToPositionWithOffset(position, 0);
        }
        componentItem.orginDataObject?.let {
            var ratio_x = 1
            var ratio_y = 1
            it.optJSONObject("other_field")?.let {
                ratio_x = it.optInt("ratio_x")
                ratio_y = it.optInt("ratio_y")
            }
            adapter.dimensionRatio = "W,${ratio_y}:${ratio_x}"
            val elements = it.optJSONArray("element")
            val size = elements.length()
            val list: MutableList<Item> = ArrayList();
            for (i in 0 until size) {
                elements.optJSONObject(i)?.let {
                    list.add(Item(it.optString("icon"), it.optString("icon_selected")))
                }
            }
            adapter.list.clear()
            adapter.list.addAll(list)
            adapter.notifyDataSetChanged()
        }


        adapterComponent?.data = contentList
        adapterComponent?.notifyItemRangeChanged(0, contentList.size)
    }


    override fun f5() {
        refreshLayout.autoRefresh(200)
    }

    override fun gun() {

    }

//
//    class Adapter(val context: Context) : BaseQuickAdapter<Item, BaseViewHolder>(R.layout.item_component89) {
//        var dimensionRatio = "W,9:16"
//        var selectPosition = 0
//        override fun convert(helper: BaseViewHolder, item: Item?) {
//            val logoIv: ImageView = helper.getView(R.id.logoIv)
//
//            if (selectPosition == helper.absoluteAdapterPosition) {
//                logoIv.load(item?.icon_selected, false, ColorDrawable(Color.WHITE))
//            } else {
//                logoIv.load(item?.icon, false, ColorDrawable(Color.WHITE))
//            }
//            val lp = logoIv.layoutParams as ConstraintLayout.LayoutParams
//            lp.dimensionRatio = dimensionRatio
//            logoIv.layoutParams = lp
//
//        }
//    }


    class Adapter(val context: Context) : BaseAdapter() {
        var dimensionRatio = "W,9:16"
        var selectPosition = 0
        val list: MutableList<Item> = ArrayList()
        override fun getCount(): Int {
            return list.size
        }

        override fun getItem(position: Int): Any {
            return list[position]
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun getView(position: Int, _convertView: View?, parent: ViewGroup?): View {
            var holder: Holder? = null

            var convertView: View? = _convertView
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.item_component89, parent, false);
                holder = Holder()
                holder.logoIv = convertView?.findViewById(R.id.logoIv)
                convertView.tag = holder
            } else {
                holder = convertView.tag as Holder
            }
            val item = list[position]
            if (selectPosition == position) {
                holder.logoIv?.load(item.icon_selected, false, ColorDrawable(Color.WHITE))
            } else {
                holder.logoIv?.load(item.icon, false, ColorDrawable(Color.WHITE))
            }
            val lp = holder.logoIv?.layoutParams as ConstraintLayout.LayoutParams
            lp.dimensionRatio = dimensionRatio
            holder.logoIv?.layoutParams = lp
            return convertView!!
        }
    }

    class Holder {
        var logoIv: ImageView? = null
    }

    data class Item(val icon: String?, val icon_selected: String?)

    override fun onDestroyView() {
        adapterComponent?.destroy()
        componentAdapter?.clearEvent()
        super.onDestroyView()
    }
}